Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 背景颜色按钮数组
    color_arr: [{
        id: '0',
        active: true,
        name: 'white',
        color: '#FFFFFF'
      },
      {
        id: '1',
        active: false,
        name: 'blue',
        color: '#428EDA'
      },
      {
        id: '2',
        active: false,
        name: 'red',
        color: '#FE0000'
      },
      {
        id: '3',
        active: false,
        name: 'gray',
        color: '#B1B1B1'
      }
    ],
    // 画布背景颜色
    canvasBackgroundColor: '#FFFFFF',
    // 画板的换算比例宽度
    canvasWidth: 200,
    // 画板的固定高度
    canvasHeight: 280,
    // 人像分离后用于生成canvas的图片
    canvasImages: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // console.log(options)
    // 导出图片的实际像素宽
    let widthPX = options.widthPX;
    // 导出图片的实际像素高
    let heightPX = options.heightPX;
    /*
     * 为了显示美观，等比例换算画布的宽，高度则固定不变
     * 换算比=》导出实际像素宽：导出实际像素高 = 画板换算比例宽度：画板固定高度
     */
    let canvasWidth = widthPX / heightPX * this.data.canvasHeight;
    // console.log(canvasWidth)
    this.setData({
      widthPX: widthPX,
      heightPX: heightPX,
      canvasWidth: canvasWidth
    })
    wx.showLoading({
      title: '生成中',
      mask: true
    })
    // 拿到截图插件返回是图片路径后先上传自己的云服务器
    wx.cloud.uploadFile({
      cloudPath: 'simpleCrop/' + parseInt(new Date().getTime() / 1000) + '.png',
      filePath: options.resultSrc, // 文件路径
    }).then(res => {
      // console.log(res.fileID)
      // 截图的云ID
      let simpleCropFileID = res.fileID;
      this.setData({
        simpleCropFileID: simpleCropFileID
      })
      // 上传到云服务器后根据fileID把截图的https链接拿回来
      wx.cloud.getTempFileURL({
        fileList: [{
          fileID: simpleCropFileID,
          maxAge: 60 * 60, // one hour
        }]
      }).then(res => {
        // console.log(res.fileList[0].tempFileURL)
        // 调用人像分离云函数，成功后会返回分离后的图片fileID
        wx.cloud.callFunction({
          name: 'SegmentPortraitPic',
          data: {
            'image': res.fileList[0].tempFileURL
          }
        }).then(res => {
          // console.log(res.result.fileID)
          // 人像分离图片的云ID
          let SegmentPortraitPicFileID = res.result.fileID;
          this.setData({
            SegmentPortraitPicFileID: SegmentPortraitPicFileID
          })
          // 根据fileID把分离后的图片https链接拿回来
          wx.cloud.getTempFileURL({
            fileList: [{
              fileID: SegmentPortraitPicFileID,
              maxAge: 60 * 60, // one hour
            }]
          }).then(res => {
            // console.log(res.fileList)
            this.setData({
              canvasImages: res.fileList[0].tempFileURL
            })
            // 初次渲染画布
            this.processingCanvas()
          }).catch(error => {
            // handle error
          })
        }).catch(error => {
          console.log(error)
          wx.showToast({
            title: '人像分离未成功！',
            icon: 'error',
            duration: 5000
          })
        })
      }).catch(error => {
        // handle error
      })
    }).catch(error => {
      // handle error
    })
  },

  // 处理画布数据
  processingCanvas() {
    wx.createSelectorQuery().select('#myCanvas').fields({
        node: true,
        size: true
      })
      .exec((res) => {
        // console.log(res)
        const canvas = res[0].node;
        // 根据系统信息来换算画布的大小
        const dpr = wx.getSystemInfoSync().pixelRatio;
        canvas.width = res[0].width * dpr
        canvas.height = res[0].height * dpr
        const ctx = canvas.getContext('2d')
        ctx.scale(dpr, dpr)
        // 填充画布的背景颜色
        ctx.fillStyle = this.data.canvasBackgroundColor;
        // 画布宽
        let canvasWidth = this.data.canvasWidth;
        // 画布高
        let canvasHeight = this.data.canvasHeight;
        // 填充画布大小
        ctx.fillRect(0, 0, canvasWidth, canvasHeight)
        let pic = canvas.createImage();
        pic.src = this.data.canvasImages;
        // console.log(pic)
        pic.onload = () => {
          // 将图片渲染到画布
          ctx.drawImage(pic, 0, 0, canvasWidth, canvasHeight);
          wx.hideLoading();
        }
      })
  },

  // 点击选择背景色按钮
  chooseColor(e) {
    // console.log(e)
    let index = e.currentTarget.dataset.index;
    // console.log(index)
    let color_arr = this.data.color_arr;
    // 清理选中状态
    color_arr.forEach(e => {
      e.active = false
    })
    // 指定选中按钮的状态
    color_arr[index].active = true;
    // 画布背景颜色
    let canvasBackgroundColor = color_arr[index].color;
    // console.log(canvasBackgroundColor)
    this.setData({
      color_arr: color_arr,
      canvasBackgroundColor: canvasBackgroundColor
    })
    // 重新渲染画布
    this.processingCanvas()
  },

  // 点击重新选图
  backPage() {
    wx.navigateBack({
      delta: 0,
    })
  },

  // 点击保存图片
  saveImages() {
    let _this = this;
    wx.showLoading({
      title: '保存中',
      mask: true
    })
    wx.createSelectorQuery().select('#myCanvas').fields({
        node: true,
        size: true
      })
      .exec((res) => {
        // console.log(res)
        const canvas = res[0].node;
        // 将画布转换成图片
        wx.canvasToTempFilePath({
          canvas: canvas,
          destWidth: this.data.widthPX,
          destHeight: this.data.heightPX,
          success(res) {
            // console.log(res.tempFilePath)
            // 把canvas合成的图片上传到服务器
            wx.cloud.uploadFile({
              cloudPath: 'IDPhoto/' + parseInt(new Date().getTime() / 1000) + '.png',
              filePath: res.tempFilePath, // 文件路径
            }).then(res => {
              // console.log(res.fileID)
              // 证件照的云ID
              let IDPhotoFileID = res.fileID;
              _this.setData({
                IDPhotoFileID: IDPhotoFileID
              })
              // 把canvas合成的图片下载下来
              wx.cloud.downloadFile({
                fileID: IDPhotoFileID, // 文件 ID
                success: res => {
                  // console.log(res.tempFilePath)
                  // 调用保存到相机
                  wx.saveImageToPhotosAlbum({
                    filePath: res.tempFilePath,
                    success: res => {
                      // console.log(res)
                      wx.hideLoading()
                      wx.showToast({
                        title: '已存到手机相册',
                        duration: 4000
                      })
                    },
                    fail: err => {
                      // console.log(err)
                      if (err.errMsg === "saveImageToPhotosAlbum:fail:auth denied" ||
                        err.errMsg === "saveImageToPhotosAlbum:fail auth deny" ||
                        err.errMsg === "saveImageToPhotosAlbum:fail authorize no response") {
                        wx.showModal({
                          title: '提示',
                          content: '需要您授权保存相册',
                          showCancel: false,
                          success: res => {
                            wx.openSetting({
                              success(settingdata) {
                                if (settingdata.authSetting['scope.writePhotosAlbum']) {
                                  // console.log('获取权限成功，给出再次点击图片保存到相册的提示。')
                                } else {
                                  // console.log('获取权限失败，给出不给权限就无法正常使用的提示')
                                }
                              }
                            })
                          }
                        })
                      }
                      wx.hideLoading()
                    }
                  })
                },
                fail: console.error
              })
            }).catch(error => {
              // console.log(error)
            })
          },
          fail: function (res) {
            // console.log(res)
          }
        })
      })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    console.log('隐藏')
    // 把服务器多余图片/文件夹清理掉
    wx.cloud.callFunction({
      name: 'ClearingRedundantFolders'
    }).then(e => {
      console.log(e)
    }).catch(error => {
      console.log(error)
    })
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    console.log('卸载')
    // 把服务器多余图片/文件夹清理掉
    wx.cloud.callFunction({
      name: 'ClearingRedundantFolders'
    }).then(e => {
      console.log(e)
    }).catch(error => {
      console.log(error)
    })
  },

})